import React from "react";

// error为渲染时抛出的异常
// https://github.com/bvaughn/react-error-boundary
type FallbackRender = (props:{error:Error | null}) => React.ReactElement
// 此处的PropsWithChildren就是type uitility,里面传入的泛型就是除Children之外剩下的属性
export class ErrorBoundary extends React.Component<React.PropsWithChildren<{ fallbackRender: FallbackRender }>, {error: Error | null}>{
  state = { error: null }

  // 当子组件抛出异常，这里会接收到并且调用
  static getDerivedStateFromError(error: Error) {
    return { error }
  }

  render() {
    const { error } = this.state
    const { fallbackRender, children } = this.props
    if (error) {
      return fallbackRender(error)
    } 
    return children
  }
}